package com.intretech.umsin.oss.util;

import com.intretech.umsin.oss.vo.FileInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.UUID;

/**
 * @version V1.0
 * @ClassName: FileUtils
 * @Description: FileUtils 服务实现
 * @author: 李启联
 * @date: 2022-04-24 22:51
 * @Copyright: Copyright (c) 2022
 */
@Slf4j
public class FileUtils {

    /**
     * 系统临时目录
     * <br>
     * windows 包含路径分割符，但Linux 不包含,
     * 在windows \\==\ 前提下，
     * 为安全起见 同意拼装 路径分割符，
     * <pre>
     *       java.io.tmpdir
     *       windows : C:\Users/xxx\AppData\Local\Temp\
     *       linux: /temp
     * </pre>
     */
    public static final String SYS_TEM_DIR = System.getProperty("java.io.tmpdir") + File.separator;
    /**
     * 定义GB的计算常量
     */
    private static final int GB = 1024 * 1024 * 1024;
    /**
     * 定义MB的计算常量
     */
    private static final int MB = 1024 * 1024;
    /**
     * 定义KB的计算常量
     */
    private static final int KB = 1024;

    /**
     * 格式化小数
     */
    private static final DecimalFormat DF = new DecimalFormat("0.00");

    /**
     * MultipartFile转File
     */
    public static File toFile(MultipartFile multipartFile) {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String suffix = "." + getExtensionName(fileName);
        File file = null;
        try {
            // 用uuid作为文件名，防止生成的临时文件重复
            file = File.createTempFile(UUID.randomUUID().toString().replace("-",""), suffix);
            // MultipartFile to File
            multipartFile.transferTo(file);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return file;
    }

    /**
     * 获取文件扩展名，不带 .
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * Java文件操作 获取不带扩展名的文件名
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    /**
     * 文件大小转换
     */
    public static String getSize(long size) {
        String resultSize;
        if (size / GB >= 1) {
            //如果当前Byte的值大于等于1GB
            resultSize = DF.format(size / (float) GB) + "GB   ";
        } else if (size / MB >= 1) {
            //如果当前Byte的值大于等于1MB
            resultSize = DF.format(size / (float) MB) + "MB   ";
        } else if (size / KB >= 1) {
            //如果当前Byte的值大于等于1KB
            resultSize = DF.format(size / (float) KB) + "KB   ";
        } else {
            resultSize = size + "B   ";
        }
        return resultSize;
    }

    /**
     * inputStream 转 File
     */
    public static File inputStreamToFile(InputStream ins, String name) throws Exception {
        File file = new File(SYS_TEM_DIR + name);
        if (file.exists()) {
            return file;
        }
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }

    public static String getFileType(String type) {
        String documents = "txt doc pdf ppt pps xlsx xls docx";
        String music = "mp3 wav wma mpa ram ra aac aif m4a";
        String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg";
        String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg";
        if (image.contains(type)) {
            return "图片";
        } else if (documents.contains(type)) {
            return "文档";
        } else if (music.contains(type)) {
            return "音乐";
        } else if (video.contains(type)) {
            return "视频";
        } else {
            return "其他";
        }
    }

    public static void checkSize(long maxSize, long size) {
        // 1M
        int len = 1024 * 1024;
        if (size > (maxSize * len)) {
            throw new RuntimeException("文件超出规定大小");
        }
    }

    /**
     * 判断两个文件是否相同
     */
    public static boolean check(File file1, File file2) {
        String img1Md5 = getMd5(file1);
        String img2Md5 = getMd5(file2);
        return img1Md5.equals(img2Md5);
    }

    /**
     * 判断两个文件是否相同
     */
    public static boolean check(String file1Md5, String file2Md5) {
        return file1Md5.equals(file2Md5);
    }

    private static byte[] getByte(File file) {
        // 得到文件长度
        byte[] b = new byte[(int) file.length()];
        try {
            InputStream in = new FileInputStream(file);
            try {
                System.out.println(in.read(b));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
            return null;
        }
        return b;
    }

    private static String getMd5(byte[] bytes) {
        // 16进制字符
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(bytes);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            // 移位 输出字符串
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 下载文件
     *
     * @param request  /
     * @param response /
     * @param file     /
     */
    public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) {
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            org.apache.poi.util.IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                    if (deleteOnExit) {
                        file.deleteOnExit();
                    }
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    public static String getMd5(File file) {
        return getMd5(getByte(file));
    }



    /**
     * 流文件输出，写入磁盘
     *
     * @param is
     * @param file
     * @throws IOException
     */
    public static void outputFile(InputStream is, File file) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        try {
            IOUtils.copy(is, fos);
        } finally {
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(is);
        }
    }



    /**
     * 文件下载,不拼接配置路径
     * @param sPath
     * @param tPath
     * @return
     * @throws IOException
     */
    public static File downloadFile4FullPath(String sPath, String tPath) throws IOException {
        File sFile = new File(sPath);
        if (StringUtils.isBlank(tPath)) {
            return sFile;
        }

        InputStream is = new FileInputStream(sFile);
        ensureDirectoryExists(tPath);
        File tFile = new File(assemblePath(tPath, sFile.getName()));
        if (!tFile.exists()) {
            tFile.createNewFile();
        }

        outputFile(is, tFile);

        return sFile;
    }

    /**
     * <p>
     * 组合路径，并转换成当前系统所适用的文件夹分隔符
     * </p>
     *
     * @param paths
     * @return
     */
    public static String assemblePath(String... paths) {
        StringBuffer fullPath = new StringBuffer();
        for (String path : paths) {
            if (StringUtils.isBlank(path)) {
                continue;
            }

            if (!StringUtils.endsWithAny(fullPath, "\\", "/") && !StringUtils.startsWithAny(path, "\\", "/")) {
                fullPath.append(File.separator);
            }
            fullPath.append(path);
        }
        if (File.separator.equals("\\")) {
            return fullPath.toString().replace("/", File.separator);
        }
        return fullPath.toString().replace("\\", File.separator);
    }



    /**
     * 确保路径存在，不存在则将创建路径
     *
     * @param path
     */
    public static void ensureDirectoryExists(String path) {
        if (StringUtils.isBlank(path)) {
            return;
        }

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }



    /**
     * 上传前定义文件的信息
     * @param file 源文件
     * @return 文件信息
     * @throws Exception
     */
    public static FileInfoVo getFileInfo(MultipartFile file) throws Exception {
        String md5 = fileMd5(file.getInputStream());

        FileInfoVo fileInfo = new FileInfoVo();
        fileInfo.setFileMd5(md5);// 将文件的md5设置为文件表的id

        if(StringUtils.isNotBlank(file.getOriginalFilename())){
            fileInfo.setName(file.getOriginalFilename());//源文件名称
            fileInfo.setFileType(FilenameUtils.getExtension(file.getOriginalFilename()));//文件扩展名
        }else{
            fileInfo.setName(file.getName());
            fileInfo.setFileType(FilenameUtils.getExtension(file.getName()));//文件扩展名
        }
        fileInfo.setContentType(file.getContentType());

        fileInfo.setSize(file.getSize());//文件大小
        fileInfo.setTagsName(UUID.randomUUID().toString().replace("-","")+"."+fileInfo.getFileType());//对应目标服务器上的文件名

        return fileInfo;
    }


    /**
     * 文件的md5
     *
     * @param inputStream
     * @return
     */
    public static String fileMd5(InputStream inputStream) {
        try {
            return DigestUtils.md5Hex(inputStream);
        } catch (IOException e) {
            log.error("FileUtil->fileMd5:{}" ,e.getMessage());
        }

        return null;
    }

    /**
     * 字符串MD5值
     * @param source
     * @return
     */
    public static String stringMd5(String source){
        try {
            return DigestUtils.md5Hex(source.getBytes("utf-8"));
        }catch (Exception e) {
            log.error("FileUtil->stringMd5:{}" ,e.getMessage());
        }
        return null;
    }

    public static String saveFile(MultipartFile file, String path) {
        try {
            File targetFile = new File(path);
            if (targetFile.exists()) {
                return path;
            }

            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);

            return path;
        } catch (Exception e) {
            log.error("FileUtil->saveFile:{}" ,e.getMessage());
        }

        return null;
    }


    public static boolean deleteFileComplete(String pathname) {
        File file = new File(pathname);
        if (file.exists()) {
            boolean flag = file.delete();

            if (flag) {
                File[] files = file.getParentFile().listFiles();
                if (files == null || files.length == 0) {
                    file.getParentFile().delete();
                }
            }

            return flag;
        }

        return false;
    }

    /**
     * 列出目录所有子集
     * @param pathname
     * @return
     */
    public static File[] listDirChildren(String pathname) {
        File dir = new File(pathname);
        if (dir.isDirectory()) {
            return dir.listFiles();
        }
        return null;
    }

    /**
     * 删除文件夹
     * @param pathname
     * @return
     */
    public static boolean deleteDir(String pathname) {
        return deleteDir(new File(pathname));
    }

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] child = dir.list();
            for (String url : child) {
                boolean isSuccess = deleteDir(new File(dir, url));
                if (!isSuccess) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    /**
     * 将文件转换成byte数组
     * @param tradeFile
     * @return
     */
    public static byte[] File2byte(File tradeFile){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            log.error("将文件转换成byte数组:",e);
        }catch (IOException e){
            log.error("将文件转换成byte数组:",e);
        }
        return buffer;
    }

}
